package com.kzd.gtgame.jetpack.vm

import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.SPStaticUtils
import com.kzd.gtgame.app.BUNDLE_KEY_SEARCH
import com.kzd.gtgame.base.BaseViewModel
import com.kzd.gtgame.entity.*
import com.kzd.gtgame.jetpack.manager.SearchRepository
import com.kzd.gtgame.utils.JsonUtils
import com.module.lemlin.http.HttpResponseBody
import com.module.lemlin.http.HttpResponseDataE
import com.module.lemlin.http.SubscribeViewModel
import java.lang.Exception

class SearchViewModel(application: Application) : BaseViewModel(application) {


    private val mSearchRepository: SearchRepository = SearchRepository()


    val mSearchRecordList: MutableList<String>
        get() {
            val search = SPStaticUtils.getString(BUNDLE_KEY_SEARCH)
            return if (search.isNullOrEmpty()) {
                mutableListOf()
            } else try {
                JsonUtils.stringToList(search, String::class.java)
                    .toMutableList()
            } catch (e: Exception) {
                mutableListOf()
            }
        }

    val keywordLiveData = MutableLiveData<String>()

    val searchRecordLiveData = MutableLiveData<MutableList<String>>()
    fun searchRecord(){
        searchRecordLiveData.postValue(mSearchRecordList)
    }

    val searchHotLiveData = MutableLiveData<HttpResponseBody<HttpResponseDataE<SearchHot>>>()
    fun searchHot() {
        setRxLifeScope(SubscribeViewModel(searchHotLiveData)) {
            mSearchRepository.searchHot()
        }
    }

    val searchDefaultLiveData = MutableLiveData<HttpResponseBody<HttpResponseDataE<SearchDefault>>>()
    fun searchList() {
        setRxLifeScope(SubscribeViewModel(searchDefaultLiveData)) {
            mSearchRepository.searchList()
        }
    }

    val searchInfoLiveData = MutableLiveData<HttpResponseBody<HttpResponseDataE<GameBean>>>()
    fun searchInfo(keyword: String) {
        setRxLifeScope(SubscribeViewModel(searchInfoLiveData)) {
            mSearchRepository.searchInfo(keyword)
        }
    }


    val searchClickLiveData = MutableLiveData<HttpResponseBody<SearchClickResponse>>()
    fun searchClick(gameId: String) {
        setRxLifeScope(object : SubscribeViewModel<SearchClickResponse>(searchClickLiveData) {
            override fun onSuccess(resp: SearchClickResponse) {
                super.onSuccess(resp.apply { this.gameId = gameId })
            }
        }) {
            mSearchRepository.searchClick(gameId)
        }
    }
}